package sasku.client.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.log4j.Logger;

public class Settings implements Serializable {

	private static final long serialVersionUID = 1L;

	/** Logger **/
	private static Logger log = Logger.getLogger(Settings.class);

	/** Name of the settings file **/
	private static final String fileName = "settings";
	private static Settings instance = load();

	private String username;
	private String password;
	private String hosts;
	private int port;

	private Settings() {
	}

	/**
	 * Loads settings from the file.
	 */
	private static Settings load() {
		log.debug("Loading settings");

		String filePath = Environment.getSettingsDirectory() + fileName;
		try {
			FileInputStream fileInputStream = new FileInputStream(filePath);
			ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
			return (Settings) objectInputStream.readObject();
		} catch (FileNotFoundException e) {
			log.debug("Settings file does not exist");
			save();
		} catch (IOException e) {
			log.warn("Failed to load settings file [" + filePath + "]", e);
		} catch (ClassNotFoundException e) {
			log.warn("Settings class does not exist", e);
		}
		
		return new Settings();
	}

	/**
	 * Saves settings to the file.
	 */
	public static void save() {
		log.debug("Saving settings");

		String filePath = Environment.getSettingsDirectory() + fileName;
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(filePath);
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
			objectOutputStream.writeObject(instance == null ? new Settings() : instance);
			objectOutputStream.close();

		} catch (FileNotFoundException e) {
			log.warn("Could not create settings file [" + filePath + "]", e);
		} catch (IOException e) {
			log.warn("Failed to write to the settings file [" + filePath + "]", e);
		}
	}

	public static Settings getInstance() {
		return instance;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = Util.toSha1(password);
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getHosts() {
		return hosts;
	}

	public void setHosts(String hosts) {
		this.hosts = hosts;
	}

}
